<?php
/*
 * IKPHP 爱客开源社区 @copyright (c) 2012-3000 IKPHP All Rights Reserved 
 * @author 小麦
 * @Email:ikphp@sina.cn 2014年8月13日13:02:26
 * 个人空间 日记
 */
namespace IKPHP\Apps\Space\Controllers;

use IKPHP\Apps\Space\Controllers;
use IKPHP\Common\Models\User;
use IKPHP\Common\Models\Images;
use IKPHP\Apps\Space\Models\UserNote;


class NotesController extends SpaceBaseController
{
	private $userid = 0;
	
    public function initialize()
    {
        parent::initialize();
        // 访问者控制
		if ($this->visitor){
			$this->userid = $this->visitor['userid'];
		}
		$this->user_mod = new User();
    }
    
    //日记首页
    public function indexAction($id = ''){
    	if(empty($id)) return $this->error ( '呃...你想要的东西不在这儿' );
    	$userid = $this->isValidUser($id);
    	$strUser = $this->user_mod->getOneUser($userid);
    	if($strUser){
    		
    		//查询日记
    		$map = "userid = '$userid' and title<>'0' ";
    		$count = UserNote::count($map);
			$pager = $this->_pager($count, 15);
			$where = array(
					"columns" => "noteid",
			 		"conditions" => $map,
		 			"order" => "addtime desc", 
		 			"limit" => array("number"=>$pager->listRows, 'offset'=>$pager->firstRow)
			);
			$list  = UserNote::find($where); 
    		$arrNote = array();
			if(count($list) > 0){
				foreach($list as $key=>$item){
					$arrNote [] = UserNote::findFirst("noteid = '$item->noteid'");
				}			
			}
    		
			$this->assign('arrNote',$arrNote);
			$this->assign('pageUrl', $pager->show());
    		
    		//最多阅读
			$hotNotes = UserNote::getHotNotes($userid,10);
			$this->assign('hotNotes', $hotNotes);
    		
			if($this->userid == $userid){
			 	$title = '我的日记';
			}else{
			 	$title = $strUser['username'].'的日记';
			}
			$this->assign('strUser',$strUser);  	
	    	$this->_config_seo ( array (
				'title' => $title,
				'subtitle'=> '_日记_'.C('ik_site_title'),
				'keywords' => '网络日记,记事本,日记,日志,相册',
				'description'=> '把生活中的点点滴滴都记录下来吧；分享生活中有意义的事情，留住青春，珍藏您一生的记忆！',
	    		'userTitle' => $title
			) );			 
		}else{
			return $this->error('呃...你想访问的页面不存在');
		}
    }
    //新建
    public function createAction(){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}  
		$userid = $this->userid;
		//查询预先数据
		$strNote = UserNote::findFirst("userid='$userid' and title= '0' ");
    	if(!$strNote){
			//新增一条
			$data['userid'] = $userid;
			$data['title'] = '0';
			$data['content'] = '0';
			$data['count_comment'] = 0;
			$data['count_view'] = 0;
			$data['count_recommend'] = 0;
			$data['count_like'] = 0;
			$data['isaudit'] = 0;
			$data['privacy'] = 1;
			$data['isreply'] = 1;
			$data['isrecommend'] = 0;
			$data['addtime'] = time();
			$data['uptime'] = time();
			$strNote = new UserNote(); 
			$newNote = $strNote->save($data);
			$noteid = $strNote->noteid;
			$this->assign('isold', false);
		}else{
			$noteid = $strNote->noteid;
			$this->assign('isold', true);
		}

		//浏览该照片
		$type = 'note';
		$arrPhotos = Images::getImagesByTypeid($type, $noteid);
		$this->assign('arrPhotos',$arrPhotos);
			
		$this->assign('strNote',$strNote);
		
		$this->_config_seo ( array (
				'title' => '新加日记',
				'subtitle'=> '_日记_'.C('ik_site_title'),
				'keywords' => '',
				'description'=> '',
		) );		
		
    }
    //开始更新
    public function updateAction(){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}  	    	
    	if(IS_POST){
    		if ($this->security->checkToken()) {
    			$userid =  $this->userid;
    			$noteid = $this->_post('noteid');
				//查询
				$strNoteObj = UserNote::findFirst("userid = '$userid' and noteid = '$noteid' ");
				if($strNoteObj){
					$strNote = $strNoteObj->toArray();
					$data['title']   = $this->_post ( 'title');
					$data['content'] = $this->_post ( 'content' );
					$data['privacy'] = $this->_post ( 'privacy' ); //隐私
					$data['isreply'] = $this->_post ( 'isreply', 'intval', 1); //是否允许评论
					$data['isaudit'] = 1; //设置为已审核
					
					if(empty($strNote['addtime'])){
						$data['addtime'] = time(); //如果存在时间不更新
					}
					
					//安全性判断
					if(empty($data ['title']) || empty($data ['content'])){
						return $this->error('标题、内容都必须填写！');
					}elseif (ck_strlen($data ['title'])>60){
						return $this->error('标题太长了，最多60个字！');
					}elseif (ck_strlen($data ['content'])>20000){
						return $this->error('文章内容太长了！');
					}

					//开始更新
					$is_save = $strNoteObj->save($data);
					if($is_save){
						/////////////执行更新图片信息/////////////
						$arrSeqid = $this->_post('seqid');
						$arrTitle = $this->_post('photodesc');
						if(is_array($arrSeqid)){
							foreach($arrSeqid as $key=>$item){
								$seqid = $arrSeqid[$key];
								$imgtitle = empty($arrTitle[$key]) ? '' : $arrTitle[$key];
								$layout = $this->_post ( 'layout_'.$seqid);
								$dataimg = array('title'=>$imgtitle, 'align'=> $layout,'typeid'=>$noteid);
								$where = "type = 'note' and typeid='$noteid' and seqid = '$seqid'";
								Images::updateImage($dataimg,$where);
							}
						}
						/////////////执行更新图片信息结束//////////////////
						
						//更新缓存文件
						$this->viewCache->delete('note-body-'.$noteid);
						
						return $this->_redirect('space/notes/show/'.$noteid);			
					}else{
						return $this->error('呃...操作失败了');
					}
				}else{
					return $this->error('呃...你没有权限访问该页面');
				}
				
    		}else{
    			return $this->error ( '呃...已经超时了' );
    		}
    	}else{
    		return $this->error('呃...你想访问的页面不存在');
    	}
    }
    /**
     * 日记显示页 URL = "/space/notes/show/11/desc/1/page/22" 规则显示
     * */
	public function showAction($id = 0 ,$page = 1){

		$order    = $this->_get('order','trim','asc');
		$isauthor = $this->_get('isauthor','trim', 0);
		
		if(!is_numeric($id) || empty($id)){
			return $this->error('呃...你想访问的页面不存在');
		}
		
		$strNote = UserNote::getOneNote($id);
		if(!$strNote){
			return $this->error('呃...你想访问的页面不存在');
		}else{	
			
			
			// TODO 未审核 和 私有的不显示		
			
			
			$strUser = User::getOneUser($strNote['userid']);
			
			$arrNotes = UserNote::getNewNotes($strNote['userid'], 10);

			//浏览数+1
			if($this->userid != $strNote['userid']){
				UserNote::findFirst("noteid = '$id'")->save(array('count_view'=>$strNote['count_view']+1));
			}		

			//获取评论 类型type 类型ID typeid 返回的连接
			$this->assign('params', array(
							'type'=>'UserNote',
							'typeid'=>$id,
							'userid'=>$strNote['userid'], 
							'link'=>'space/notes/show',
							'order'=>$order,
							'isauthor'=>$isauthor,
							'page'=>$page
			));
			//评论list结束	

			//sns组件开始
			$this->assign('snsparams', array(
							'type'=>'UserNote',
							'typeid'=>$id,
							'userid'=>$strNote['userid'], 
							'title' =>$strNote['title'],
							'content' =>sub_str(clearText($strNote['content']),200),
							'href'  =>'space/notes/show/'.$id,
							'headimg'  =>$strNote['headimg'],
							'count_recommend'  =>$strNote['count_recommend'],
							'count_like'  =>$strNote['count_like'],		
							'link'=>'space/notes/show',
							'page'=>$page
			));
			//sns end			
			
			$this->assign('strNote',$strNote);
			$this->assign('strUser',$strUser);
			$this->assign('arrNotes',$arrNotes);
			
			$this->_config_seo ( array (
					'title' => $strNote['title'],
					'subtitle'=> '_日记_'.C('ik_site_title'),
					//'keywords' => ikscws($strNote ['title']),
					'keywords'	=> '网络日记,记事本,日记,日志,相册',
					'description'=> sub_str(clearText($strNote['content']),200),
					'userTitle' => $strUser['username'].'的日记'
			) );			
		}
	}
	public function editAction($id){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}
		$userid = $this->userid;
		$noteid = (int)$id;
		//查询预先数据
		$strNote = UserNote::findFirst(array("noteid = '$noteid' and userid = '$userid'"));
		if(!$strNote){$this->error('呃...你没有权限访问该页面');}

		//浏览该照片
		$type = 'note';
		$arrPhotos = Images::getImagesByTypeid($type, $noteid);
		$this->assign('arrPhotos',$arrPhotos);
				
		$this->assign('strNote',$strNote);
		$this->_config_seo ( array (
				'title' => '编辑日记',
				'subtitle'=> '_日记_'.C('ik_site_title'),
				'keywords' => '',
				'description'=> '',
		) );	
	}
	//删除日记
	public function deleteAction($id){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}
		$userid = $this->userid;
		$noteid = (int)$id;
		$strNote = UserNote::findFirst(array("noteid = '$noteid' and userid = '$userid'"));
		if(!$strNote){return $this->error('呃...你没有权限删除该日记');}
		//删除
		$strNote->delete();
		$this->_redirect('space/'.$this->visitor['doname'].'/notes/');
	}    
}